import { Service } from 'egg';
import { Result } from '../util/result';
import MsgEnum from '../util/msgEnum';
import { v4 as uuidv4 } from 'uuid';

export default class Product extends Service {
  async getList(page: number) {
    let transaction;
    try {
      transaction = await this.ctx.model.transaction();

      const results = await this.ctx.model.TalentClassfication.findAndCountAll(
        {
          distinct: true,
          offset: Number((page - 1) * 10),
          limit: 10,
        },
        { transaction }
      );

      await transaction.commit();

      return new Result({
        rows: results.rows,
        count: results.count,
      });
    } catch (e) {
      await transaction.rollback();
      return new Result(null, MsgEnum.SERVER_ERROR);
    }
  }
  async insert(typeName: string, typeDescription: string) {
    let transaction;
    try {
      transaction = await this.ctx.model.transaction();

      const res = await this.ctx.model.TalentClassfication.create(
        {
          uuid: uuidv4().replace(/-/g, ''),
          typeName,
          typeDescription,
        },
        { transaction }
      );

      await transaction.commit();

      return new Result(res);
    } catch (e) {
      await transaction.rollback();
      return new Result(null, MsgEnum.SERVER_ERROR);
    }
  }
  async del(uuid: string) {
    const { ctx } = this;
    let transaction;
    try {
      transaction = await ctx.model.transaction();

      const type = await ctx.model.TalentClassfication.findOne(
        {
          where: { uuid },
        },
        { transaction }
      );
      type;

      const talents = await ctx.model.Talent.findAll(
        {
          include: [
            {
              model: ctx.model.Patent,
            },
          ],
          where: {
            pk_type: uuid,
          },
        },
        { transaction }
      );

      for (const talent of talents) {
        console.log(talent);
        for (const patent of talent.patents) {
          console.log(patent);
          await patent.merge_patent_talent.destroy({ transaction });
        }
        await talent.destroy({ transaction });
      }

      await type.destroy({ transaction });

      await transaction.commit();

      return new Result({
        status: 'success',
      });
    } catch (e) {
      console.log(e);
      await transaction.rollback();
      return new Result(null, MsgEnum.SERVER_ERROR);
    }
  }

}
